﻿using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;
using System.Activities;
using System.Activities.Expressions;
using System.Activities.Presentation.PropertyEditing;
using System.Activities.Statements;
using System.Collections.Generic;
using System.ComponentModel;
using FTP = FTPSClient;
using System.Windows.Markup;

namespace Vision.Core.ActivityComponents.IO.Ftp
{
    /// <summary>
    /// 
    /// </summary>
    [ContentProperty("Body")]
	[Designer(typeof(FtpDownloadFileDesigner))]
	public class FtpDownloadFile : NativeActivity
    {
        /// <summary>
        /// 
        /// </summary>
        internal FTP.FTPSClient FtpClient { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public InArgument<string> FileName { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public OutArgument<byte[]> FileData { get; set; }

		/// <summary>
		/// 
		/// </summary>
		public ActivityAction<byte[]> Body { get; set; }

		public FtpDownloadFile()
		{
			this.Body = new ActivityAction<byte[]>()
			{
				Argument = new DelegateInArgument<byte[]>()
				{
					Name = "downloadData"
				}
			};
		}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(NativeActivityContext context)
        {
            byte[] file = null;
            
            this.FtpClient = (FTP.FTPSClient)context.Properties.Find("5AED2CE1-FB3C-45B3-9CB7-3DC8CD5E4C56");
                        
            if (this.FtpClient != null){
                string fileName = context.GetValue(this.FileName);                
                using (Stream stream = this.FtpClient.GetFile(fileName)){
                    using (MemoryStream output = new MemoryStream()){
                        using (BinaryWriter writer = new BinaryWriter(output)){
                            byte[] buf = new byte[1024];
                            int n = 0;
                            do{
                                n = stream.Read(buf, 0, buf.Length);
                                if (n > 0){
                                    writer.Write(buf, 0, n);
                                }
                            }
                            while (n > 0);
                        }
                        file = output.ToArray();
                    }                    
                }
            }

			if (this.Body != null && this.Body.Handler != null)
				context.ScheduleAction<byte[]>(this.Body, file);

            context.SetValue(this.FileData, file);
        }
    }
}
